
function TrackInfo(id){
	if(!id) return null;

	var self = this,
		data = null;
	try{
		data = JSON.parse(localStorage.getItem(id));
	} catch(e){}
	
	this.id = id;
	this.statuses = data?$.map(data, function(status){
		return new TrackStatus(status.data);
	}):[];
	console.log(this.statuses);
	this.toHTML = function(){
		return "<table cellspacing=0 cellpadding=2>" + $.map(this.statuses, function(status){
			//console.log(status)
			return status.toRow();
		}).join("\n")+ "</table>";
	};
	
	this.save = function(){
		localStorage.setItem(id, JSON.stringify(this.statuses));
	};
	
	this.update = function(callback){
		startAnimate();
		this.updated = false;
		$.each(oServices, function(i, service){
			service.update(self.id, function(trackStatus){
				if(trackStatus && typeof trackStatus == 'object'){
					if($.grep(self.statuses, function(ts){
						return ts.compare(trackStatus);
					}).length == 0){
						self.updated = true;
						console.log('new trackStatus: ', trackStatus);
						self.statuses.push(trackStatus);
						self.save();
						if(callback)
							callback(trackStatus);						
					}
				}
			});
		});
	};

}


function TrackStatus(data){
	this.data = $.extend({
		date: null,
		status: '',
		summary: '',
		service: '',
		place: ''
	}, data);
	this.toRow = function(){
		return "<tr><td><img src=\"img/" + this.data.service + ".ico\" title=\""+this.data.service+"\" width=16 height=16/></td><td>" + ((typeof this.data.date == 'string')?this.data.date:this.data.date.format("dd.mm.yy hh:mm")) + "</td><td>" + this.data.status + "</td><td>" + this.data.summary + "</td><td>" + this.data.place + "</td></tr>";
	};
	this.compare = function(ts){
		return ts.data.status==this.data.status && ts.data.summary==this.data.summary && ts.data.service==this.data.service;
	};
}

function Service (){
        this.className = 'Service';
}
Service.prototype.sendRequest = function(data){
	$.ajax(data);

}

function RussianPost(){
        this.constructor.apply(this, arguments);
        this.className = 'RussianPost';
}
RussianPost.prototype = new Service();
RussianPost.prototype.update = function(id, callback){
	this.sendRequest({
			url: "http://www.russianpost.ru/resp_engine.aspx?Path=rp/servise/ru/home/postuslug/trackingpo",
			type: "POST",
			data: {
				'BarCode': id,
				'OP': '',
				'PATHCUR': 'rp/servise/ru/home/postuslug/trackingpo',
				'PATHFROM': '',
				'WHEREONOK': '',
				'ASP': '',
				'PARENTID': '',
				'FORUMID': '',
				'NEWSID': '',
				'DFROM': '',
				'DTO': '',
				'CA': '',
				'CDAY': '',
				'CMONTH': '',
				'CYEAR': '',
				'NAVCURPAGE': '',
				'SEARCHTEXT': '',
				'PATHWEB': 'RP/INDEX/RU/Home',
				'PATHPAGE': 'RP/INDEX/RU/Home/Search',
				'search1': '',
				'searchsign': '1',
				'searchbarcode': ''
			},
			success: function(data){
				
					var $context = $("<div />").html(data.replace(/(?:script|link|img)/g,'div'))
						$trs = $context.find("table.pagetext tbody tr");
						$trs.each(function(i, tr){
							var $tr = $(tr);
							try{
								var status = $tr.children("td").eq(0).text()
									summary = $tr.children("td").eq(4).text(),
									date =  $tr.children("td").eq(1).text(),
									place = $tr.children("td").eq(2).text() +", " +$tr.children("td").eq(3).text();						
								if(status && summary){
									if(callback)
										callback(new TrackStatus({
											date: date,
											status: status,
											summary: summary,
											place: place,
											service: 'RussianPost'
										}));
								}
							}catch(e){}
						});
					$context.remove();
			
			},
			error: function(){
				if(callback) callback(null);
			}
		});
}

function USPSPost(){
        this.constructor.apply(this, arguments);
        this.className = 'USPSPost';
}
USPSPost.prototype = new Service();
USPSPost.prototype.update = function(id, callback){
	var self = this;
	this.sendRequest({
			url: "https://tools.usps.com/go/TrackConfirmAction.action",
			type: "POST",
			data: {
				'tLabels': id
			},
			success: function(data){
				//console.log(data);
				try {
					var $context = $("<div />").html(data.replace(/(?:script|link|img)/g,'div')),
						status = $("span#status", $context).text(),
						summary = $("span#summary", $context).text();
					if(status && summary){
						callback(new TrackStatus({
							date: new Date(),
							status: status,
							summary: summary,
							service: 'USPSPost'
						}));
					}
					$context.remove();
				} catch(e) {
					if(callback) callback(null);
				}
			},
			error: function(){
				if(callback) callback(null);
			}
		});
}

function RoyalMail(){
        this.constructor.apply(this, arguments);
        this.className = 'RoyalMail';
}
RoyalMail.prototype = new Service();
RoyalMail.prototype.update = function(id, callback){
	var self = this;
	this.sendRequest({
			url: "http://www2.royalmail.com/track-trace",
			type: "POST",
			data: {
				'track_id': id,
				'op': 'Track',
				'form_build_id': 'form-9077b661d005de149af1fa20c8e281a3',
				'form_id': 'track_trace_request_form'
			},
			success: function(data){
				//console.log(data);
				try {
					var $context = $("<div />").html(data.replace(/(?:script|link|img)/g,'div')),
						status = $('div#tnt-results h2.title:first', $context).text(),
						summary = $('div#tnt-results p:first', $context).text();
					if(summary && status && status !='Sorry'){
						callback(new TrackStatus({
							date: new Date(),
							status: status,
							summary: summary,
							service: 'RoyalMail'
						}));
					}
					$context.remove();
				} catch(e) {
					if(callback) callback(null);
				}
			},
			error: function(){
				if(callback) callback(null);
			}
		});
}

function SingaporePost(){
        this.constructor.apply(this, arguments);
        this.className = 'SingaporePost';
}
SingaporePost.prototype = new Service();
SingaporePost.prototype.update = function(id, callback){
	var self = this;
	this.sendRequest({
			url: "http://www.singpost.com/index.php",
			type: "GET",
			data: {
				'ranumber': id,
				'option': 'com_tablink',
				'controller': 'tracking',
				'task': 'trackdetail',
				'layout': 'show_detail',
				'tmpl': 'component',
			},
			success: function(data){
				try {
					var $context = $("<div />").html(data.replace(/(?:script|link|img)/g,'div')),
						$table = $('form div table tr table tbody tr[align=center]', $context);
					//console.log($table);
					$table.each(function(i, tr){
						if (i == 0) return;
						var $tr = $(tr);
						try{
							var date = $tr.children("td").eq(0).text(),
								sumCell = $tr.children("td").eq(1).html().split("<br>"),
								status = (sumCell.length>1)?sumCell[0]:"",
								summary = (sumCell.length>1)?sumCell[1]:sumCell[0];	
					
							if(date && summary){
								if(callback)
									callback(new TrackStatus({
										date: date,
										status: status,
										summary: summary,
										place: "",
										service: 'SingaporePost'
									}));
							}
						}catch(e){}
					});
					$context.remove();
				} catch(e) {
					if(callback) callback(null);
				}
			},
			error: function(){
				if(callback) callback(null);
			}
		});
}
function DHLGlobalMail(){
        this.constructor.apply(this, arguments);
        this.className = 'DHLGlobalMail';
}
DHLGlobalMail.prototype = new Service();
DHLGlobalMail.prototype.update = function(id, callback){
	var self = this;
	this.sendRequest({
			url: "http://webtrack.dhlglobalmail.com",
			type: "GET",
			data: {
				'trackingnumber': id
			},
			success: function(data){
				try {
					var $context = $("<div />").html(data.replace(/(?:script|link|img)/g,'div')),
						$table = $('table#tracking_table tbody tr', $context).reverse();
					//console.log($table);
					$table.each(function(i, tr){
						var $tr = $(tr);
						try{
							var date = $tr.children("td").eq(0).text() + " " + $tr.children("td").eq(1).text(),
								summary = $tr.children("td").eq(3).text(),
								place = $tr.children("td").eq(2).text();	
					
							if(date && summary){
								if(callback)
									callback(new TrackStatus({
										date: date,
										status: "",
										summary: summary,
										place: place,
										service: 'DHLGlobalMail'
									}));
							}
						}catch(e){}
					});
					$context.remove();
				} catch(e) {
					if(callback) callback(null);
				}
			},
			error: function(){
				if(callback) callback(null);
			}
		});
}
var oServices = [new RussianPost(), new USPSPost(), new RoyalMail(), new SingaporePost(), new DHLGlobalMail()];

